<!-- eslint-disable no-unused-expressions -->
<!-- eslint-disable radix -->
<!-- eslint-disable no-useless-escape -->
<!-- eslint-disable no-param-reassign -->
<!--
 * @Description: Description
 * @Author: Kerwin
 * @Date: 2023-10-13 11:41:12
 * @LastEditTime: 2024-07-05 11:14:12
 * @LastEditors:  Please set LastEditors
-->
<!-- eslint-disable no-shadow -->
<!-- eslint-disable no-console -->
<!-- eslint-disable no-use-before-define -->
<template>
  <view class="container">
    <view class="topBox">
      <view class="action">
        <u-icon color="#fff" :size="40" name="reload" @click="refresh"></u-icon>
        <view class="mine" @click="jump">
          <u-image width="50rpx" height="50rpx"
            src="https://image.blacksilverscore.com/uploads/6844def4-1bf8-40ce-8995-a0043bf8e5cf.png"></u-image>
        </view>
      </view>
      <view class="tit">{{ siteInfo.name }}</view>
      <view class="wrap">
        <view>设备使用说明：</view>
        <view>1.若使用押金方式使用，前三小时免费，超过三小时后2元一小时，从押金中扣除，封顶66元</view>
        <view>2.归还充电宝，结束计费，若押金有剩余，将原路退回您的账户</view>
        <!-- <view>计费规则：</view>
        <view>1.前24小时免费，超过24小时后2元一个小时</view>
        <view>2.总封顶99元</view> -->
      </view>
    </view>
    <!-- <view class="section">
      <view class="tit">支付方式说明</view>
      <view> 余额:余额中扣除费用 </view>
      <view> 优惠券:优惠券在洗车过程中会被优先抵扣使用 </view>
    </view> -->
    <view class="img_box">
      <image src="https://image.blacksilverscore.com/uploads/88b4d5ba-0361-4482-85bf-fc449361f0ae.jpg" mode="scaleToFill"
        class="img" />
    </view>
    <view class="selector" @click="showSelect">
      <view>{{ selectedConfig.name }}</view>
      <u-icon name="arrow-down" color="#666"></u-icon>
    </view>
    <u-select v-model="show" label-name="name" value-name="type" :list="configDetails" @confirm="confirm"></u-select>
    <!-- 押金支付方式选择 -->
    <view class="payment_box" v-if="selectedConfig.type == 72">
      <view class="tit">支付方式选择</view>
      <view class="wrap">
        <u-radio-group v-model="selectPaymentType">
          <u-radio v-for="(item, index) in paymentTypeOptions" :key="index" :name="item.paymentType">
            {{ item.paymentTypeName }}
          </u-radio>
        </u-radio-group>
      </view>
    </view>
    <view class="btn_wrap">
      <view class="order_tips" v-for="(item, index) in orders" :key="index">
        <u-notice-bar mode="horizontal" :list="[item.text]" :volume-icon="false" :more-icon="true"></u-notice-bar>
      </view>

      <u-button ripple :hair-line="false" class="btn" :custom-style="{ background: '#50939c', color: '#fff' }"
        @click="getWxPayScore" :loading="loading" :disabled="orders?.length > 0" v-if="env === 'app' && selectedConfig.type == 83">
        免押租借
      </u-button>
      <u-button v-else-if="!orders?.length && selectedConfig.type == 72" ripple :hair-line="false" class="btn"
        :custom-style="{ background: '#50939c', color: '#fff' }" @click="payDeposit">
        支付押金 {{ depositMoney }} 元
      </u-button>
      <u-button v-else ripple :hair-line="false" class="btn" :custom-style="{ background: '#50939c', color: '#fff' }"
        @click="submit" :loading="loading" :disabled="orders?.length > 0">点击弹出充电宝</u-button>
      <!-- 免押租借 -->
      <!-- <view class="tips" v-if="env === 'app'"><u-icon size="46"
          name="https://image.blacksilverscore.com/uploads/c1f45d56-0d6c-4308-8f77-0203209b4d05.png" mr3
          style="margin-right: 10rpx"></u-icon>
        <text>微信⽀付分|550及以上有机会免押</text>
      </view> -->
      <view class="check">
        <u-checkbox v-model="checked" :label-size="26">
          勾选表示同意<text style="color: #65a674" @click="toAuthLetter">《委托扣款授权书》</text></u-checkbox>
      </view>
    </view>
    <u-popup v-model="mask" :mask-close-able="false" :border-radius="12" mode="center" width="400rpx" height="280rpx">
      <view class="mask_tips"> 请使用黑银APP扫码 </view>
      <view v-if="configStore.isWeChatBrowser" style="padding:0 20rpx">（点击右上角"...",在手机自带浏览器打开，按提示下载）</view>
      <view v-else class="open_app" @click="openApp"> 打开黑银APP <u-icon name="arrow-right" size="28" color="blue"></u-icon>
      </view>
    </u-popup>
  </view>
</template>
<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { onLoad, onShow, onReady } from '@dcloudio/uni-app'
import { storeToRefs } from 'pinia'
import { baseApi, powerBankApi, userApi } from '@/api'
import { checkLoginState, getImgFullPath } from '@/utils/index'
import { useUserStore, useConfigStore } from '@/store'
import {
  browserVersion,
  compareVersion,
  qs,
  getQueryVariable,
  launchClientApp
} from '@/utils/common'

const userStore = useUserStore()
const configStore = useConfigStore()
const { userInfo, hasLogin } = storeToRefs(userStore)
const deviceInfo = ref({})
const siteInfo = ref({})
const deviceSn = ref('')
const serviceType = ref(8)
const loading = ref(false)
const checked = ref(false)
const show = ref(false)
const configDetails = ref([])
const selectedConfig = ref({})
function showSelect() {
  show.value = true
}
function confirm(e: { value: any }[]) {
  const { value } = e[0]
  selectedConfig.value =
    configDetails.value.find((item) => item.type === value) || {}
}

async function getDetail() {
  uni.showLoading({
    mask: true
  })
  const { data } = await powerBankApi
    .getDeviceDetail({
      deviceSn: deviceSn.value
    })
    .finally(() => {
      uni.hideLoading()
    })
  siteInfo.value = data?.site
}

const outOrderNo = ref('')
const paymentSubType = ref(4) // h5=4，app=11
// 启动设备
async function start(params?: { paymentType: any }) {
  uni.showLoading({
    title: '启动中'
  })
  loading.value = true
  const obj = {
    deviceSn: deviceSn.value,
    serviceType: serviceType.value,
    consumeType: selectedConfig.value.type,
    paymentType: params?.paymentType || 1,
    paymentSubType: paymentSubType.value,
    paymentId: outOrderNo.value
  }
  const { code, message } = await powerBankApi.deviceStart(obj).finally(() => {
    loading.value = false
    uni.hideLoading()
  })
  if (code === 0) {
    uni.showModal({
      title: '提示',
      content: message,
      showCancel: false,
      confirmText: '确认',
      success: ({ confirm }) => {
        if (confirm) {
          refresh()
        }
      }
    })
  } else {
    uni.showModal({
      title: '提示',
      content: message,
      showCancel: false,
      confirmText: '确认'
    })
  }
}
// 获取消费类型相关信息（及配置项）

async function getOrderConsumeType() {
  const { data } = await powerBankApi.getOrderConsumeType({
    deviceSn: deviceSn.value
  })
  configDetails.value = data?.orderConsumeTypeConfig?.configDetails
  selectedConfig.value = configDetails.value[0] || {}
  deviceInfo.value = data?.device

  // 押金相关
  const yajinObj = configDetails.value.find((item) => item.type === 72)
  if (yajinObj) {
    getOptions(yajinObj)
  }
}


// 押金
const paymentTypeOptions = ref([])
const selectPaymentType = ref(null)
const depositMoney = ref(0)
function getOptions(obj: { config: string }) {
  const data = JSON.parse(obj.config)
  paymentTypeOptions.value = data.paymentTypeList
  selectPaymentType.value = data.paymentTypeList[0].paymentType
  depositMoney.value = data.depositMoney
}
const yupengAppId = 'wx41dc0a5bba8478fb'
async function getCode() {
  // 授权玉鹏的公众号
  const { result } = await powerBankApi.getWxPublicAccountOpenId()
  console.log('result========>', result)
  console.log('openId========>', result.openId)
  if (result.openId) {
    openId.value = result.openId
    payDeposit()
  } else {
    wxAuth(yupengAppId)
  }
}
function wxAuth(appid: string) {
  console.log('进入跳转方法===>', appid)
  const APPID = appid
  const SCOPE = 'snsapi_userinfo'
  const REDIRECT_URL = encodeURIComponent(
    `https://wap.blacksilverscore.com/#/packageB/pages/powerBank/detail?deviceSn=${deviceSn.value}&appId=${appid}`
  )
  console.log('进入跳转方法===>url', REDIRECT_URL)
  setTimeout(() => {
    window.open(
      `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${APPID}&redirect_uri=${REDIRECT_URL}&response_type=code&scope=${SCOPE}&state=STATE#wechat_redirect`
    )
  })
}
const openId = ref('')
async function getWxPublicAccountOpenId(code: string) {
  const { result } = await powerBankApi.postWxPublicAccountOpenId({
    code
  })
  openId.value = result.openId
  payDeposit()
}

// 支付押金
async function payDeposit() {
  uni.showLoading()
  const params = JSON.parse(selectedConfig.value?.config)
  console.log(selectPaymentType.value, '999')
  if (!selectPaymentType.value) {
    uni.showToast({
      icon: 'none',
      title: '请选择支付方式'
    })
    return
  }
  const paymentTypeObj = paymentTypeOptions.value.find((item) => item.paymentType === selectPaymentType.value)
  const paymentSubType = paymentTypeObj?.paymentSubTypeList[0]?.paymentSubType
  const paySuccessHandler = JSON.stringify({
    type: 1,
    data: {
      deviceSn: deviceSn.value,
      serviceType: serviceType.value,
      consumeType: selectedConfig.value.type,
      paymentType: selectPaymentType.value,
      paymentSubType: paymentSubType,
      paymentId: outOrderNo.value
    }
  })
  const _data = {
    amount: params.depositMoney,
    paymentSubType: paymentSubType,
    paymentType: selectPaymentType.value,
    walletType: 68,
    type: 4,
    openId: openId.value,
    deviceId: deviceInfo.value?.id,
    paySuccessHandler
  }
  const queryString = qs(_data)
  const { data } = await powerBankApi.pay(queryString).finally(() => {
    uni.hideLoading()
  })
  if (data?.payResponse?.payment) {
    outOrderNo.value = data?.payResponse?.payment.id
    delete data?.payResponse?.payment
  }
  if (selectPaymentType.value === 62) {
    //支付宝
    const payment_id = data?.payment.id
    uni.setStorageSync('payment_id', payment_id)
    sftAliPay_qr(data.payResponse)
  } else {
    nativeWxPay(data.payResponse)
  }

  // uni.showLoading()
  // const params = JSON.parse(selectedConfig.value?.config)
  // const data = {
  //   amount: params.depositMoney,
  //   paymentSubType: params.paymentSubType,
  //   paymentType: 1,
  //   walletType: 68,
  //   type: 4,
  //   openId: openId.value
  // }
  // const queryString = qs(data)
  // const { result } = await powerBankApi.pay(queryString).finally(() => {
  //   uni.hideLoading()
  // })
  // if (result.payment) {
  //   outOrderNo.value = result.payment.id
  //   delete result.payment
  // }
  // nativeWxPay(result)
}

// 支付宝支付-盛付通(qr)
function sftAliPay_qr(params: { payInfo: any }) {
  console.log('pay_params==>', params)
  const { payInfo } = params
  location.href = payInfo
}

function nativeWxPay(data: any) {
  // #ifdef H5
  if (typeof WeixinJSBridge === 'undefined') {
    if (document.addEventListener) {
      document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false)
    } else if (document.attachEvent) {
      document.attachEvent('WeixinJSBridgeReady', onBridgeReady)
      document.attachEvent('onWeixinJSBridgeReady', onBridgeReady)
    }
  } else {
    onBridgeReady(data)
  }
  // #endif
}
// 微信支付
function onBridgeReady(data: any) {
  console.log('微信支付参数==>', data)
  WeixinJSBridge.invoke(
    'getBrandWCPayRequest',
    {
      appId: data.appId,
      timeStamp: data.timeStamp,
      nonceStr: data.nonceStr,
      package: data.package,
      signType: data.signType,
      paySign: data.paySign
    },
    (res: { err_msg: string }) => {
      if (res.err_msg === 'get_brand_wcpay_request:ok') {
        // 使用以上方式判断前端返回,微信团队郑重提示：
        // res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
        start()
      }
    }
  )
}

function jump() {
  uni.navigateTo({
    url: '/packageB/pages/powerBank/mine'
  })
}

// 获取进行中的订单
const orders = ref()
async function getOrderInProgress() {
  const { data } = await powerBankApi.getCustomerWashingOrders({
    serviceType: serviceType.value
  })
  data.forEach(
    (item: {
      serviceType: any
      text: string
      deviceDetail: { site: { name: any } }
    }) => {
      switch (item?.washOrder?.serviceType) {
        case 8:
          item.text = `充电宝使用中！-${item.deviceDetail?.site?.name}-归还后可继续弹出充电宝`
          break
        default:
          item.text = `设备使用中！-${item.deviceDetail?.site?.name}`
          break
      }
    }
  )
  orders.value = data
}
const env = ref('')
async function queryStart() {
  const { data } = await powerBankApi.queryScoreServiceOrder({
    outOrderNo: outOrderNo.value,
    paymentSubType: paymentSubType.value
  })
  if (data?.state === 'DOING') {
    start()
  } else {
    uni.showToast({
      icon: 'none',
      title: '支付分未授权'
    })
  }
}
/**
 * 跳转微信支付分
 */
function goToWXScore(queryString: any) {
  jWeixin.checkJsApi({
    jsApiList: ['openBusinessView'], // 需要检测的JS接口列表
    success(res: { checkResult: { openBusinessView: any } }) {
      // 以键值对的形式返回，可用的api值true，不可用为false
      // 如：{"checkResult":{"openBusinessView":true},"errMsg":"checkJsApi:ok"}
      if (res.checkResult.openBusinessView) {
        WeixinJSBridge.invoke(
          'openBusinessView',
          {
            businessType: 'wxpayScoreUse',
            queryString
          },
          async (res: { err_code: string }) => {
            // 从支付分返回时会执行这个回调函数
            if (parseInt(res.err_code) === 0) {
              // 返回成功
              queryStart()
            } else {
              // 返回失败
              console.log(res)
              console.log(queryString)
              uni.showToast({
                icon: 'none',
                title: '支付分授权失败'
              })
            }
          }
        )
      }
    }
  })
}
// 获取微信支付分
async function getWxPayScore() {
  if (!checked.value) {
    uni.showToast({
      icon: 'none',
      title: '请勾选委托扣款授权书'
    })
    return
  }
  if (browserVersion().isHeiyin) {
    // ios client ios拦截不了请求，下面的请求由ios自行发起
    window.JSBridge.invoke('CallWXScoreService', {
      bridgeName: 'deviceStart',
      paymentSubType: paymentSubType.value
    })
    return
  }
  const { data } = await powerBankApi.createScoreServiceOrder({
    paymentSubType: paymentSubType.value
  })
  const wechatInfo = navigator.userAgent.match(/MicroMessenger\/([\d\.]+)/i)
  const wechatVersion = wechatInfo[1]
  if (compareVersion(wechatVersion, '7.0.5') >= 0) {
    const obj = {
      mch_id: data.mchId,
      package: data.package,
      timestamp: data.timestamp,
      nonce_str: data.nonceStr,
      sign_type: data.signType,
      sign: data.sign
    }
    outOrderNo.value = data.outOrderNo
    const paramsArray: string[] = []
    Object.keys(obj).forEach(
      (key) => obj[key] && paramsArray.push(`${key}=${obj[key]}`)
    )
    goToWXScore(`${paramsArray.join('&')}`)
  } else {
    // 提示用户升级微信客户端版本
    window.href =
      'https://support.weixin.qq.com/cgi-bin/readtemplate?t=page/common_page__upgrade&text=text005&btn_text=btn_text_0'
  }
}
function toAuthLetter() {
  uni.navigateTo({
    url: '/packageB/pages/powerBank/authLetter'
  })
}
function refresh() {
  const { origin, pathname, hash } = window.location
  window.location.href = `${origin + pathname + hash}`
}
const mask = ref(false)
function openApp() {
  mask.value = false
  uni.showLoading({
    title: '正在打开APP'
  })
  setTimeout(() => {
    uni.hideLoading()
  }, 2000)
  launchClientApp(() => {
    mask.value = true
  })
}

const submit = () => {
  if (!checked.value) {
    uni.showToast({
      icon: 'none',
      title: '请勾选委托扣款授权书'
    })
    return
  }
  const { type } = selectedConfig.value
  switch (type) {
    case 72:
      getCode()
      break
    case 5:
      start()
      break
    default:
      console.log(type)
  }
}
// 获取支付状态
function getPaymentStatus() {
  const id = uni.getStorageSync('payment_id')
  if (!id) return
  powerBankApi.getPaymentById({
    id
  })
}

onShow(async () => {
  await getOrderInProgress()
  await getPaymentStatus()
})

onLoad(async (option) => {
  deviceSn.value = option?.deviceSn
  if (option?.serviceType) {
    serviceType.value = option?.serviceType
  }
  console.log('deviceSn==>', deviceSn.value)
  console.log('serviceType==>', serviceType.value)
  const isApp = option?.from || browserVersion().isHeiyin
  console.log('isApp==>', isApp)

  if (isApp) {
    // #ifdef H5
    console.log('前端注册回调时机==>', new Date())
    window.JSBridge.registerEvent('HYUserEvent', () => {
      getDetail()
      getOrderInProgress()
      getOrderConsumeType()
    })
    window.JSBridge.registerEvent(
      'deviceStart',
      (data: { outOrderNo: string }) => {
        outOrderNo.value = data.outOrderNo
        queryStart()
      }
    )
    env.value = 'app'
    paymentSubType.value = 1
    // #endif
  } else {
    if (browserVersion().mobile && !configStore.isWeChatBrowser) {
      // 非微信浏览器端不请求接口了，只作为打开app的入口
      mask.value = true
      return
    }
    await getDetail()
    await getOrderInProgress()
    await getOrderConsumeType()
    mask.value = true
    // 跳转其他公众号授权后返回得
    const code = getQueryVariable('code')
    if (code && option?.appId === yupengAppId) {
      checked.value = true
      getWxPublicAccountOpenId(code)
    }
  }
})
</script>


<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background-color: #fff;

  .topBox {
    background: #50939c;
    padding: 40rpx;

    .tit {
      font-size: 36rpx;
      color: #fff;
    }

    .wrap {
      background: rgba(255, 255, 255, 0.4);
      border-radius: 20rpx;
      color: #fff;
      padding: 10rpx 20rpx;
      line-height: 44rpx;
      margin-top: 20rpx;
      font-size: 26rpx;
    }

    .action {
      display: flex;
      justify-content: space-between;
      margin-bottom: 10rpx;
      align-items: center;
    }
  }

  .section {
    padding: 30rpx;
    line-height: 50rpx;
  }

  .img_box {
    .img {
      width: 100%;
      margin-top: 100rpx;
    }
  }
}

.selector {
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2rpx solid #ccc;
  border-radius: 8rpx;
  padding: 20rpx 0;
  gap: 10rpx;
  margin: 20rpx 30rpx 30rpx 30rpx;
}

.payment_box {
  padding: 0 30rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .tit {
    margin-bottom: 10rpx;
    font-weight: bold;
  }
}

.btn_wrap {
  margin: 30rpx 30rpx 0 30rpx;
  padding-bottom: 80rpx;

  .btn {
    // position: absolute;
    bottom: 0;
    left: 0;
    // width: 100%;
    height: 100rpx;
    border-radius: 20rpx;
  }

  :deep(.u-btn--default--disabled) {
    opacity: 0.5;
  }

  .order_tips {
    margin-bottom: 30rpx;
  }
}

.check {
  text-align: center;
  margin-top: 30rpx;
  font-size: 24rpx;
}

.mask_tips {
  text-align: center;
  font-size: 30rpx;
  font-weight: bold;
  margin-top: 60rpx;
}

.tips {
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 30rpx;
}

.open_app {
  margin-top: 30rpx;
  text-align: center;
  color: blue;
}
</style>
